package com.gitee.cnzhangjie.excel.convert;

import com.gitee.cnzhangjie.excel.ExcelException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;

/**
 * Workbook创建工厂
 */
final class WorkbookFactory {
    /**
     * 根据类型创建Workbook
     * 用于excel file->java bean
     *
     * @param excelType   类型
     * @param inputStream 输入流
     * @return Workbook
     * @throws ExcelException excel异常
     */
    static Workbook create(final ExcelType excelType, final InputStream inputStream) throws ExcelException {
        if (excelType == null) {
            throw new NullPointerException("this excelType argument must not be null");
        }
        if (inputStream == null) {
            throw new NullPointerException("this inputStream argument must not be null");
        }
        switch (excelType) {
            case XLS:
                try {
                    return new HSSFWorkbook(inputStream);
                } catch (IOException e) {
                    throw new ExcelException("hssf create fail, type is xls, msg:" + e.getMessage());
                }
            case XLSX:
                try {
                    return new XSSFWorkbook(inputStream);
                } catch (IOException e) {
                    throw new ExcelException("xssf create fail, type is xlsx, msg:" + e.getMessage());
                }
            case BIG_XLSX:
                try {
                    return new SXSSFWorkbook(new XSSFWorkbook(inputStream));
                } catch (IOException e) {
                    throw new ExcelException("sxssf create fail, type is xlsx, msg:" + e.getMessage());
                }
            default:
                throw new ExcelException(excelType + " type is not support");
        }
    }

    /**
     * 根据类型创建Workbook
     * 用于java bean->excel file
     *
     * @param excelType 类型
     */
    static Workbook create(final ExcelType excelType) throws ExcelException {
        if (excelType == null) {
            throw new NullPointerException("this excelType argument must not be null");
        }
        switch (excelType) {
            case XLS:
                return new HSSFWorkbook();
            case XLSX:
                return new XSSFWorkbook();
            case BIG_XLSX:
                return new SXSSFWorkbook();
            default:
                throw new ExcelException(excelType + " type is not support");
        }
    }
}
